/*
 * Copyright (c) 1989, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef lint
#if 0
static char sccsid[] = "@(#)parse.c	8.1 (Berkeley) 6/6/93";
#endif
#endif /* not lint */
#include <sys/types.h>
#include <ctype.h>
#include <err.h>
#include <fcntl.h>
#ifdef DEBUG
#include <inttypes.h>
#endif
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hexdump.h"

FU *endfu;					/* format at end-of-data */

#ifdef DEBUG
#define TRACEBACK	warnx("%s:%d", __FILE__, __LINE__)
#else
#define TRACEBACK
#endif
#define	BADCNT(s)	TRACEBACK; badcnt(s)
#define BADCONV(s) 	TRACEBACK; badconv(s)
#define BADFMT(fmt)	TRACEBACK; badfmt(fmt)

void
addfile(char *name)
{
	FILE *fp;
	char *buf, *lbuf, *p;
	size_t len;

	if ((fp = fopen(name, "r")) == NULL)
		err(1, "%s", name);

	lbuf = NULL;
	while ((buf = fgetln(fp, &len)) != NULL) {
		if (buf[len-1] == '\n')
			buf[len-1] = '\0';
		else {

			/* EOF without EOL, copy and add the NUL */
			if ((lbuf = malloc(len + 1)) == NULL)
				err(EXIT_FAILURE, "%s:%d", __FILE__, __LINE__);
			memcpy(lbuf, buf, len);
			lbuf[len] = '\0';
			buf = lbuf;

		}
		for (p = buf; isspace(*p); p++) ;
		if (*p != '\0' && *p != '#')
			add(p);
	}

	if (lbuf != NULL)
		free(lbuf);
	(void)fclose(fp);

}

void
add(const char *fmt)
{
	static FS **nextfs;
	FS *tfs;
	FU *tfu, **nextfu;
	char *p_start, *p, *savep;
	long tmp_long;

	/* start new linked list of format units */
	if ((tfs = calloc(1, sizeof(FS))) == NULL)
		err(1, "%s:%d", __FILE__, __LINE__);
	if (!fshead)
		fshead = tfs;
	else
		*nextfs = tfs;
	nextfs = &tfs->nextfs;
	nextfu = &tfs->nextfu;

	/* 
	 * Take the format string and break it up into format units.
	 *
	 * The structure of each format unit is as follows:
	 *
	 * 	iteration_count/byte_count
	 *
	 * iteration_count and byte_count are optional, but either one or the
	 * other must be present if the partitioning '/' is present.
	 *
	 * Iteration count defaults to 1, and byte count defaults vary
	 * depending upon the format string specified. See size for more
	 * details.
	 */

	/* XXX (gcooper): Uck.. this is nasty and it needs fixing. */
	if ((p = strdup(fmt)) == NULL)
		err(EXIT_FAILURE, "%s:%d", __FILE__, __LINE__);

	p_start = p;

	while (*p != '\0') {

		/* Skip any and all leading white space. */
		for (; isspace(*p); p++) ;

		/* There's more information on the line to scan. */
		if (*p != '\0') {

			/* allocate a new format unit and link it in */
			if ((tfu = calloc(1, sizeof(FU))) == NULL)
				err(EXIT_FAILURE, "%s:%d", __FILE__, __LINE__);
			*nextfu = tfu;
			nextfu = &tfu->nextfu;
			/* Default to one iteration count. */
			tfu->reps = 1;

			/*
			 * We only want non-zero numbers for the repetition
			 * count and the byte count. All negative numbers would
			 * be caught below at the == '"' check, and would
			 * subsequently fail because the leading character is `-'.
			 */

			/* Scan the repetition count. */
			if (isdigit(*p)) {

				savep = p;
				tmp_long = strtol(savep, &p, 10);

				/* 
				 * There _must_ be a following slash; avoid
				 * overflow.
				 */
				if (*p != '/' || tmp_long == 0 ||
				    tmp_long > INT_MAX) {
					BADFMT(fmt);
				}

				tfu->reps = (int) tmp_long;
				tfu->flags = F_SETREP;

			}

			/* Scan the byte count. */
			if (*p == '/' && isdigit(*++p)) {

				savep = p;
				tmp_long = strtol(savep, &p, 10);
				/* 
				 * There _must_ be following whitespace for the
				 * byte count; avoid overflow.
				 */
				if (!isspace(*p) || tmp_long == 0 ||
				    tmp_long > INT_MAX) {
					BADFMT(fmt);
				}

				tfu->bcnt = (int) tmp_long;

			}

			/* Skip trailing white space */
			while (isspace(*p)) p++;

			/* This wasn't a valid format string */
			if (*p++ != '"') {
				BADFMT(fmt);
			}
			/* Copy the format string between the '"' terminators. */
			for (savep = p; *p != '"'; p++) {

				/* The format string isn't valid (couldn't find
				 * a '"' terminator) */
				if (*p == '\0') {
					BADFMT(fmt);
				}

			}
			if (!(tfu->fmt = malloc(p - savep + 1)))
				err(1, "%s:%d", __FILE__, __LINE__);
			(void) strlcpy(tfu->fmt, savep, p - savep + 1);
			/* End format string copy. */
			escape(tfu->fmt);
			p++;

		}

	}

	/*
	 * Avoid failed assertion in malloc(3) when the contents of *p are
	 * exhausted
	 */
	free(p_start);

}

static const char *non_numeric_spec = ".#-+ ";

/*
 * Calculate the size for a series of format units.
 *
 * The size of each format unit can be derived as follows:
 * 1. User specified a valid byte-count.
 * 2. The size must be derived from a combination of the inherent byte-count
 *    for a format qualifier, as well as the width specified with the precision
 *    qualifier. The width is generally optional, but is absolutely required
 *    for %s style format qualifier statements as the standard behavior for %s
 *    is to slurp up all characters instead of just one character.
 */
int
size(FS *fs)
{
	FU *fu;
	char *fmt, *fmt_tmp;
	long precision;
	size_t bcnt, cursize;

	/* figure out the data block size needed for each format unit */
	for (cursize = 0, fu = fs->nextfu; fu != NULL; fu = fu->nextfu) {

		bcnt = fu->bcnt;

		if (bcnt == 0) {

			for (precision = 0, fmt = fu->fmt; *fmt != '\0';
			    fmt++) {

				if (*fmt == '%') {

					/*
					 * Skip any special chars minus `.'.
					 * Save precision in case it's a %s
					 * format.
					 *
					 * Don't worry about '\0'. None of the
					 * branches below will accept '\0' as
					 * a truth in the boolean statements.
					 */
					while (strchr(non_numeric_spec+1,
					    *++fmt) != NULL) ;

					fmt_tmp = fmt;
					precision = strtol(fmt, &fmt_tmp, 10);
					if (*fmt_tmp == '.')
						precision = strtol(++fmt_tmp,
						    &fmt, 10);
					else
						fmt = fmt_tmp;
					/* 
					 * We can't be sure with absolute
					 * clarity that the precision is
					 * correct until we look at the big
					 * picture in rewrite(). Thus the range
					 * needs to be 0-exclusive.
					 *
					 * FWIW this value only matters for
					 * %...s as shown below.
					 */
					if (precision < 0 ||
					    precision > INT_MAX)
						errx(EXIT_FAILURE,
						    "Bad precision value: %s",
						    fmt);

					switch(*fmt) {
					case 'c':
						bcnt += 1;
						break;
					case 'd': case 'i': case 'o': case 'u':
					case 'x': case 'X':
						bcnt += 4;
						break;
					case 'e': case 'E': case 'f': case 'g':
					case 'G':
						bcnt += 8;
						break;
					case 's':
						if (precision == 0)
							badsfmt();
						bcnt += (size_t) precision;
						break;
					case '_':
						switch(*++fmt) {
						case 'c': case 'p': case 'u':
							bcnt += 1;
							break;
						/* 
						 * This isn't overly apparent,
						 * but a* and A* aren't noted
						 * here because they don't
						 * `consume bytes' directly,
						 * but instead rely on other
						 * format units to consume
						 * bytes for them.
						 */
						}

					}

				}

			}

		}

#ifdef DEBUG
		printf("'%s': bytecount = %lu, reps = %d\n",
		    fu->fmt, bcnt, fu->reps);
#endif

		cursize += bcnt * fu->reps;

	}

	return (cursize);

}

void
rewrite(FS *fs)
{
	PR *pr, **nextpr;
	FU *fu;
	char cs[3], stop_scanning;
	char *p1, *p2, *fmtp;
	int nconv, nprecs;
	long field_width, precision;

	for (fu = fs->nextfu; fu != NULL; fu = fu->nextfu) {
		/*
		 * Break each format unit into print units; each conversion
		 * character gets its own.
		 *
		 * 1. fmtp is the format string pointer.
		 * 2. nconv corresponds to the number of conversion characters
		 *    (%c, %s, %_u, etc) encountered.
		 * 3. p1 is the first portion of the precision string.
		 * 4. cs is the rewritten precision qualifier.
		 * 5. p2 is the second portion of the precision string
		 *    (trailing spaces, newlines, etc).
		 *
		 */
		nextpr = &fu->nextpr;
		for (fmtp = fu->fmt, field_width = nconv = precision = 0;
		    *fmtp != '\0';
		    nextpr = &pr->nextpr, nconv++) {

			if ((pr = calloc(1, sizeof(PR))) == NULL)
				err(1, "%s:%d", __FILE__, __LINE__);
			*nextpr = pr;

			/*
			 * Skip preceding text and up to the next unescaped
			 * % sign.
			 */
			nprecs = 0;
			p1 = fmtp;
			stop_scanning = 0;
			do {

#ifdef DEBUG
				printf("fmtp: '%s', p1: '%s'\n", fmtp, p1);
#endif

				if (*p1 == '\0')
					stop_scanning = 1;
				else if (*p1 == '%') {
					nprecs++;
					if (*(p1+1) != '%')
						stop_scanning = 1;
				}

				if (stop_scanning == 0)
					p1++;

			} while (stop_scanning == 0);

			/*
			 * Only text in the string. This occurs when:
			 * 1. The contents of the string are exhausted.
			 * 2. The number of precision qualifiers (%) is even.
			 */
#ifdef DEBUG
			printf("nprecs: %d\n", nprecs);
#endif
			if (*p1 == '\0' || (nprecs % 2 == 0)) {
#ifdef DEBUG
				printf("Text-only format: '%s'\n", fmtp);
#endif
				pr->fmt = fmtp;
				pr->flags = F_TEXT;
				break;
			}

			/*
			 * Get precision for %s -- if we have a byte count, we
			 * don't need the precision.
			 */
			while (strchr(non_numeric_spec+1, *++p1) != NULL) ;

			field_width = strtol(p1, &p2, 10);
			if (field_width < 0 || INT_MAX < field_width) {
				BADFMT(fmtp);
			}
#ifdef DEBUG
			printf("%s:%d p1: '%s', p2: '%s'\n",
			    __FILE__, __LINE__, p1, p2);
#endif
			/* Forward ho! */
			p1 = p2;

			if (*p1 == '.') {
				precision = strtol(p1+1, &p2, 10);
				p1 = p2;
			}
			/*
			 * Otherwise we need to take the value last parsed,
			 * and plug it in as the precision.
			 */
			else
				if (precision < 0 || INT_MAX < precision) {
					BADFMT(fmtp);
				}

			/* 
			 * If we have a byte count, we don't need the
			 * precision. However... if both items are set, then
			 * we need to bail as we don't know which item to
			 * trust.
			 */
			if (fu->bcnt != 0) {
				if (precision == 0)
					precision = fu->bcnt;
			}

#ifdef DEBUG
			printf("%s:%d p1: '%s', p2: '%s'\n",
			    __FILE__, __LINE__, p1, p2);
#endif

			/* NUL terminate the conversion string. */
			cs[0] = *p2;
			cs[1] = '\0';
			cs[2] = '\0';

			/*
			 * Figure out the byte count for each conversion;
			 * rewrite the format as necessary, set up blank-
			 * padding for end of data.
			 */
			switch(*p2) {
			case 'c':
				pr->flags = F_CHAR;
				switch(fu->bcnt) {
				case 0: case 1:
					pr->bcnt = 1;
					break;
				default:
					p1[1] = '\0';
					BADCNT(p1);
				}
				break;
			case 'd': case 'i':
			case 'o': case 'u': case 'x': case 'X':
				if (*p2 == 'd' || *p2 == 'i')
					pr->flags = F_INT;
				else
					pr->flags = F_UINT;
				cs[0] = 'q';
				cs[1] = *p2;
				switch(fu->bcnt) {
				case 0:
					pr->bcnt = 4;
					break;
				case 1: case 2: case 4:
					pr->bcnt = fu->bcnt;
					break;
				default:
					p1[1] = '\0';
					BADCNT(p1);
				}
				break;
			case 'e': case 'E': case 'f': case 'g': case 'G':
				pr->flags = F_DBL;
				switch(fu->bcnt) {
				case 0:	case 8:
					pr->bcnt = 8;
					break;
				case 4:
					pr->bcnt = 4;
					break;
				default:
					if (fu->bcnt == sizeof(long double)) {
						cs[0] = 'L';
						cs[1] = *p2;
						pr->bcnt = sizeof(long double);
					} else {
						p1[1] = '\0';
						BADCNT(p1);
					}
				}
				break;
			case 's':
				pr->flags = F_STR;
				if (precision == 0)
					badsfmt();
				pr->bcnt = (int) precision;
				cs[0] = *p2;
				break;
			case '_':
				switch(*(p2+1)) {
				case 'A':
					endfu = fu;
					fu->flags |= F_IGNORE;
					/* FALLTHROUGH */
				case 'a':
					pr->flags = F_ADDRESS;
					switch(*(p2+2)) {
					case 'd': case 'o': case 'x':
						cs[0] = 'q';
						cs[1] = *(p2+2);
						break;
					default:
						p1[3] = '\0';
						BADCONV(p1);
					}
					break;
				case 'c': case 'p': case 'u':
					cs[0] = 'c';
					cs[1] = '\0';
					if (p1[1] == 'c')
						pr->flags = F_C;
					else if (p1[1] == 'p') {
						pr->flags = F_P;
					} else /* p1[1] == 'u' */
						pr->flags = F_U;
					switch(fu->bcnt) {
					case 0: case 1:
						pr->bcnt = 1;
						break;
					default:
						p1[2] = '\0';
						BADCNT(p1);
					}
					break;
				default:
					p1[2] = '\0';
					BADCONV(p1);
				}
				p2 += 2;
				break;
			default:
				p1[1] = '\0';
				BADCONV(p1);
			}

			p2++;

			/*
			 * Copy to PR format string, set conversion character
			 * pointer, update original format string.
			 */
			p1[0] = '\0';

#ifdef DEBUG
			printf("%s:%d &fmtp = %p &p1 = %p, &p2 = %p, cs: '%s', "
			    "fmt: '%s', p1: '%s', p2: '%s'\n",
			    __FILE__, __LINE__, fmtp, p1, p2, cs, fmtp, p1, p2);
#endif

			/* 
			 * Instead of rolling our own logic, let's just use
			 * asprintf(3). This is required to not overly
			 * complicate validating the length of prec, and the
			 * previous logic was doing similar unnecessarily.
			 *
			 * This is sufficiently bounded by the above logic
			 * that the potential for buffer overrun is low / zero.
			 */
			if (asprintf(&pr->fmt, "%s%s", fmtp, cs) == -1)
				err(EXIT_FAILURE, "%s:%d", __FILE__, __LINE__);

			/* 
			 * Record the starting address of the conversion
			 * character; this will be modified somewhere in
			 * conv_c() or in bpad().
			 */
			pr->cchar = pr->fmt + (p1 - fmtp);
			fmtp = p2;

			/* Only one conversion character if byte count. */
			if ((pr->flags & F_ADDRESS) == 0 && 0 < fu->bcnt &&
			    0 < nconv)
				errx(EXIT_FAILURE,
				    "byte count with multiple conversion "
				    "characters: %s", pr->fmt);

		}
		/*
		 * If format unit byte count not specified, figure it out
		 * so can adjust rep count later.
		 */
		if (fu->bcnt == 0)
			for (pr = fu->nextpr; pr != NULL; pr = pr->nextpr)
				fu->bcnt += pr->bcnt;
	}
	/*
	 * If the format string interprets any data at all, and it's
	 * less than the blocksize, and its last format unit
	 * interprets any data at all, and has no iteration count,
	 * repeat as necessary.
	 *
	 * If, rep count is greater than 1, no trailing whitespace
	 * gets output from the last iteration of the format unit.
	 *
	 * FIXME (gcooper): That explanation sucks. Improve it.
	 */
	for (fu = fs->nextfu; fu != NULL; fu = fu->nextfu) {
		if (!fu->nextfu && fs->bcnt < blocksize &&
		    !(fu->flags & F_SETREP) && fu->bcnt)
			fu->reps += (blocksize - fs->bcnt) / fu->bcnt;
		if (fu->reps > 1 && fu->nextpr != NULL) {
			pr = fu->nextpr;
			while (pr->nextpr != NULL)
				pr = pr->nextpr;
			for (p1 = pr->fmt, p2 = NULL; *p1 != '\0'; p1++)
				p2 = isspace(*p1) ? p1 : NULL;
			if (p2 != NULL)
				pr->nospace = p2;
		}
	}
#ifdef DEBUG
	for (fu = fs->nextfu; fu != NULL; fu = fu->nextfu) {
		(void)printf("fmt:");
		for (pr = fu->nextpr; pr; pr = pr->nextpr)
			(void)printf(" {%s}", pr->fmt);
		(void)printf("\n");
	}
#endif
}

void
escape(char *p1)
{
	char *p2;

	/* Alphabetic escape sequences have to be done in place */
	for (p2 = p1; *p1 != '\0'; p1++, p2++) {

		if (*p1 == '\\') {

			/* Do an 'atomic' peek at the next index. */
			switch(*(p1+1)) {
			case '0':
				*p2 = '\0';
				break;
			case 'a':
			     /* *p2 = '\a'; */
				*p2 = '\007';
				break;
			case 'b':
				*p2 = '\b';
				break;
			case 'f':
				*p2 = '\f';
				break;
			case 'n':
				*p2 = '\n';
				break;
			case 'r':
				*p2 = '\r';
				break;
			case 't':
				*p2 = '\t';
				break;
			case 'v':
				*p2 = '\v';
				break;
			default:
				*p2 = *(p1+1);
				break;
			}
			/*
			 * Don't overstep p1's bounds when a format string
			 * looks like: "...\" (last character is a '\'). A
			 * cleaner solution to NetBSD PR/28157 as this avoids
			 * having multiple exits to the function.
			 */
			if (*p1 != '\0')
				p1++;

		} else
			*p2 = *p1;

	}

	/* Terminate with a NUL so we truncate unneeded characters. */
	*p2 = '\0';

}

void
badcnt(char *s)
{
	errx(EXIT_FAILURE, "%s: bad byte count", s);
}

void
badsfmt(void)
{
	errx(EXIT_FAILURE, "%%s: requires a precision or a byte count");
}

void
badfmt(const char *fmt)
{
	errx(EXIT_FAILURE, "\"%s\": bad format", fmt);
}

void
badconv(char *ch)
{
	errx(EXIT_FAILURE, "%%%s: bad conversion character", ch);
}
